import request from "../../utils/request.js"
import PubSub from 'pubsub-js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
		bannersList:[],// 轮播图数据
		result:[], //推荐歌单
    topList:[], //排行榜数据
    index:0,
    allTopList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad:async function (options) {
      this.getData();

      // 订阅来自songDetail页面发布的消息
		PubSub.subscribe('switchType', (msg, type) => {
      let {allTopList, index} = this.data;
      if(type === 'pre'){ // 上一首
        (index === 0) && (index = allTopList.length);
        index -= 1;
      }else { // 下一首
        (index === allTopList.length - 1) && (index = -1);
        index += 1;
      }
      
      // 更新下标
      this.setData({
        index
      })
      
      let musicId = allTopList[index].id;
      // 将musicId回传给songDetail页面
      PubSub.publish('musicId', musicId)
      
      });
    },
    async getData(){
      const res = await request('/banner',{type:2});//轮播图
		if(res.code==200){
			this.setData({bannersList: res.banners});
		}
		
		const res1 = await request('/personalized',{limit:10});//推荐歌单
		if(res1.code==200){
			this.setData({result: res1.result});
		}
		
		let index = 0;
		let resultArr = [];
		while(index<6){
			const res2 = await request('/top/list',{idx:index++});//排行榜
			if(res2.code==200){
        // console.log(res2);
				let topListItem = {name: res2.playlist.name, tracks:res2.playlist.tracks.slice(0, 5)};
				resultArr.push(topListItem)
        this.setData({topList: resultArr})      
      }
    }
    let {topList, allTopList} = this.data

    topList.forEach(item => {
        allTopList.push(...item.tracks)
    })
    this.setData({
      allTopList
    })
  },
    meiRiTuiJian(){
      wx.reLaunch({
        url: '/pages2/tuiJianMusic/tuiJianMusic'
        })
    },
    toRege(e){
      let {song, index} =e.currentTarget.dataset
      this.setData({
        index
      })
      wx.navigateTo({
        url: '/pages2/songDetail/songDetail?id='+song.id
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})